package com.etv.launcher.ui.component;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Outline;
import android.graphics.drawable.GradientDrawable;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewOutlineProvider;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.etv.launcher.common.enums.DesktopItemEnum;
import com.etv.launcher.common.utils.ObjectUtil;
import com.etv.launcher.common.utils.UnitUtil;
import com.etv.launcher.model.dto.ApplicationInfoDto;
import com.etv.launcher.ui.actvity.desktop.DesktopFragment;

import java.io.File;

import lombok.Getter;
import lombok.Setter;

public class ApplicationIconView extends ConstraintLayout {

    @Setter
    private DesktopFragment desktopFragment;

    private static final float DEFAULT_SCALE = 1.14f;
    private static final int ANIM_DURATION = 200;

    private static final int ICON_SIZE_DP = 64;
    private static final int TEXT_MARGIN_START_DP = 12;

    private final ImageView iconView;
    private final TextView labelView;

    private String applicationId;

    private ImageView bannerView;

    private float cornerRadius;

    // 新增默认宽高
    @Getter
    private static final int DEFAULT_WIDTH_DP = 200;

    @Getter
    private static final int DEFAULT_HEIGHT_DP = 100;
    private double scaleAmount = 1;

    private static final int BG_PADDING_DP = 8;

    private final GradientDrawable backgroundDrawable;

    // 修改构造函数支持传入宽高
    public ApplicationIconView(Context context) {
        this(context, DEFAULT_WIDTH_DP, DEFAULT_HEIGHT_DP);
        this.setListener();
    }

    public ApplicationIconView(Context context, double viewScale) {
        this(context, (int) (DEFAULT_WIDTH_DP*viewScale), (int) (DEFAULT_HEIGHT_DP*viewScale));
        this.setListener();
    }

    public ApplicationIconView(Context context, int widthDp, int heightDp) {
        super(context);
        this.setListener();
        scaleAmount = UnitUtil.dpToPx(getResources(),DEFAULT_WIDTH_DP)/Double.valueOf(widthDp);

        // 设置固定宽高
        LayoutParams params = new LayoutParams(widthDp, heightDp);
        setLayoutParams(params);

        //背景组件
        backgroundDrawable = new GradientDrawable();
        setBackground(backgroundDrawable);

        // 动态生成视图ID
        int iconId = View.generateViewId();
        int textId = View.generateViewId();

        // 创建子视图
        iconView = createIconView(iconId);
        labelView = createLabelView(textId);
        bannerView = new ImageView(getContext());
        bannerView.setId(View.generateViewId());
        LayoutParams bannerParams = new LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT
        );
        bannerView.setLayoutParams(bannerParams);
        bannerView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        bannerView.setVisibility(GONE);

        // 添加视图
        addView(iconView);
        addView(labelView);
        addView(bannerView);

        // 设置约束关系
        applyConstraints(iconId, textId);

        // 焦点系统配置
        initFocusBehavior();

        //裁剪出圆角
        setClipToOutline(true);
        setOutlineProvider(new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), cornerRadius);
            }
        });
    }

    private ImageView createIconView(int viewId) {
        ImageView iv = new ImageView(getContext());
        iv.setId(viewId);

        // 图标尺寸保持不变
        LayoutParams params = new LayoutParams(
                UnitUtil.dpToPx(getResources(), ICON_SIZE_DP/scaleAmount),
                UnitUtil.dpToPx(getResources(), ICON_SIZE_DP/scaleAmount)
        );
        params.startToStart = LayoutParams.PARENT_ID;
        params.topToTop = LayoutParams.PARENT_ID;
        params.bottomToBottom = LayoutParams.PARENT_ID;

        // 通过外边距实现左边距和顶边距
        int paddingPx = UnitUtil.dpToPx(getResources(), BG_PADDING_DP);
        params.setMargins(paddingPx,paddingPx,0,0);
        iv.setLayoutParams(params);
        iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
        return iv;
    }

    private TextView createLabelView(int viewId) {
        TextView tv = new TextView(getContext());
        tv.setId(viewId);
        // 关键改动：宽度设置为MATCH_CONSTRAINT（0dp）
        LayoutParams params = new LayoutParams(
                0,  // 宽度设为0dp（MATCH_CONSTRAINT）
                LayoutParams.WRAP_CONTENT
        );
        params.startToEnd = iconView.getId();
        params.endToEnd = LayoutParams.PARENT_ID;
        params.topToTop = LayoutParams.PARENT_ID;
        params.bottomToBottom = LayoutParams.PARENT_ID;

        // 通过外边距实现右边距和底边距
        int paddingPx = UnitUtil.dpToPx(getResources(), BG_PADDING_DP);
        params.setMargins(0, 0, paddingPx, paddingPx);

        // 新增：保持原有文本边距
        params.setMarginStart(UnitUtil.dpToPx(getResources(), TEXT_MARGIN_START_DP));
        tv.setLayoutParams(params);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        tv.setMaxLines(2);
        tv.setTextColor(Color.WHITE);
        tv.setEllipsize(TextUtils.TruncateAt.END);
        tv.setIncludeFontPadding(false);

        // 新增：设置垂直居中对齐
        params.verticalBias = 0.5f;

        return tv;
    }

    private void applyConstraints(int iconId, int textId) {
        // 关键点：手动建立链式约束
        ConstraintSet set = new ConstraintSet();
        set.clone(this);


        // 关键改动：使用CHAIN_SPREAD模式并设置权重
        set.createHorizontalChain(
                ConstraintSet.PARENT_ID, ConstraintSet.LEFT,
                ConstraintSet.PARENT_ID, ConstraintSet.RIGHT,
                new int[]{iconId, textId},
                new float[]{1f, 3f}, // 设置权重比例（1:3）
                ConstraintSet.CHAIN_SPREAD
        );

        // 垂直居中约束保持不变
        set.connect(iconId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        set.connect(iconId, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);
        set.connect(textId, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);
        set.connect(textId, ConstraintSet.BOTTOM, ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM);

        set.applyTo(this);
    }

    private void initFocusBehavior() {
        setOnFocusChangeListener((v, hasFocus) -> {
            animate().cancel();
            float scale = hasFocus ? DEFAULT_SCALE : 1f;
            animate()
                    .scaleX(scale)
                    .scaleY(scale)
                    .setDuration(ANIM_DURATION)
                    .withLayer()
                    .start();
            setElevation(hasFocus ? 8f : 2f);
        });

        setFocusable(true);
        setFocusableInTouchMode(true);
        setClickable(true);
        setClipChildren(false);
    }

    /**
     * 动态圆角设置
     *
     * @param radiusDp 圆角
     */
    public void setCornerRadius(float radiusDp) {
        float px = UnitUtil.dpToPx(getResources(), radiusDp);
        this.cornerRadius = px;
        backgroundDrawable.setCornerRadius(px);

        // 同步更新硬件层裁剪
        invalidateOutline();
        invalidate();
    }

    /**
     * 数据绑定
     *
     * @param info
     */
    public void bind(ApplicationInfoDto info) {
        if (ObjectUtil.isBlank(info.getApplicationId())){
            return;
        }

        this.applicationId = info.getApplicationId();

        setBackground(backgroundDrawable);

        // 优化：仅在模式切换时更新视图
        if (ObjectUtil.isNotBlank(info.getBannerPath())) {
            showBannerMode(info.getBannerPath());
        } else {
            showNormalMode(info.getAppName(), info.getIconPath(), info.getBackColor());
        }

        this.setCornerRadius(info.getIconRadius());
    }

    private void showBannerMode(String bannerPath) {
        bannerView.setVisibility(VISIBLE);
        iconView.setVisibility(GONE);
        labelView.setVisibility(GONE);

        // 设置Banner图片（示例使用Glide）
        Glide.with(this)
                .load(new File(bannerPath))
                .override(bannerView.getWidth(), bannerView.getHeight())
                .transform(new CenterCrop()) // 移除RoundedCorners转换
                .into(bannerView);

        // 强制更新裁剪
        updateOutline();
    }

    private void updateOutline() {
        invalidateOutline();
    }

    private void showNormalMode(String label, String iconPath,int color) {
        // 普通模式
        bannerView.setVisibility(GONE);
        iconView.setVisibility(VISIBLE);
        labelView.setVisibility(VISIBLE);

        // 设置原有内容
        labelView.setText(label);
        Glide.with(this)
                .load(new File(iconPath))
                .override(iconView.getWidth(), iconView.getHeight())
                .transform(new CenterCrop()) // 移除RoundedCorners转换
                .into(iconView);

        backgroundDrawable.setColor(color);
        setBackground(backgroundDrawable);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        animate().cancel();
        iconView.setImageDrawable(null);
    }

    private void setListener(){
        setOnClickListener(v -> {
            if (this.applicationId != null && !this.applicationId.isEmpty()) {
                Intent intent = getContext().getPackageManager().getLaunchIntentForPackage(this.applicationId);
                if (intent != null) {
                    getContext().startActivity(intent);
                }
            }
        });


        setOnLongClickListener(v -> {
            desktopFragment.changeFragment(DesktopItemEnum.APPLICATIONS,applicationId);
            return true;
        });
    }
}
